package com.hz.friends.activity;

import java.io.File;
import java.io.FileOutputStream;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;

import com.hz.friends.global.Global;

public abstract class SelectPhotoActivity extends BaseActivity {
	private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果
	private  String SIMAGE_FILE_LOCATION = null;
	private File largepic_file = null;
	private File smallpic_file = null;
	private boolean issmallpic = false;
	private int size = 0;
	private Callback mcallback = null;
	private final String dirPath =  Environment.getExternalStorageDirectory()+ "/"+Global.productName +"/Image/";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	public Callback getMcallback() {
		return mcallback;
	}

	public void setMcallback(Callback mcallback) {
		this.mcallback = mcallback;
	}

	public File getLargepic_file() {
		return largepic_file;
	}

	public void setLargepic_file(File largepic_file) {
		this.largepic_file = largepic_file;
	}

	public File getSmallpic_file() {
		return smallpic_file;
	}

	public void setSmallpic_file(File smallpic_file) {
		this.smallpic_file = smallpic_file;
	}

	public boolean isIssmallpic() {
		return issmallpic;
	}

	public void setIssmallpic(boolean missmallpic) {
		this.issmallpic = missmallpic;
	}

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}


	
	// 提示对话框方法
	public void getPhoto(String titlename) {
		 if (!android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
	             .getExternalStorageState())){
			 showToast("sdcard不可用");
			 return;
		 }
		//每次复原状态，清空上次状态
		
		 SIMAGE_FILE_LOCATION = dirPath + System.currentTimeMillis()+".jpg";
		 
		if (!new File(dirPath).exists()) {
			new File(dirPath).mkdirs();
		}
		 largepic_file = null;
		 smallpic_file = null;
		
		
		 String[] items = new String[] { "选择本地图片", "拍照" };
		new AlertDialog.Builder(this)
				.setTitle(titlename)
				.setItems(items, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (which == 0) {
							//相册选择
							Intent intent = new Intent(Intent.ACTION_PICK, null);
							intent.setDataAndType(
									MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
									"image/*");
							startActivityForResult(intent, PHOTO_REQUEST_GALLERY);

						} else {
							// 调用系统的拍照功能
							Intent intent = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);
							startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
						}
					}
				}).setNegativeButton("取消", null).show();
	}

	
	public void takePhoto(){

		 if (!android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
	             .getExternalStorageState())){
			 showToast("sdcard不可用");
			 return;
		 }
		//每次复原状态，清空上次状态
		
		 SIMAGE_FILE_LOCATION = dirPath + System.currentTimeMillis()+".jpg";
		 
		if (!new File(dirPath).exists()) {
			new File(dirPath).mkdirs();
		}
		 largepic_file = null;
		 smallpic_file = null;

		// 调用系统的拍照功能
		Intent intent = new Intent(
				MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
	
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub

		switch (requestCode) {
		case PHOTO_REQUEST_TAKEPHOTO:
			if (data != null) {
				Bundle bundle = data.getExtras();
				// 拍照取消
				if (bundle == null)
					return;
				Bitmap bitmap = (Bitmap) bundle.get("data");
//				File largefile = new File(LIMAGE_FILE_LOCATION);
				largepic_file = saveMyBitmap(System.currentTimeMillis()
						+ ".jpg", bitmap);
//				if(!largefile.exists())
//					return;
//				largepic_file = largefile;
				if (issmallpic)
					startPhotoZoom(Uri.fromFile(largepic_file));
				else {
					if (mcallback != null)
						mcallback.dosomething();
				}
			}
			break;

		case PHOTO_REQUEST_GALLERY:
			if (data != null) {
				Uri uri = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(uri, filePathColumn,
						null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String picturePath = cursor.getString(columnIndex);
				cursor.close();
				largepic_file = new File(picturePath);
				if (issmallpic){
					startPhotoZoom(data.getData());
				}
				else {
					if (mcallback != null)
						mcallback.dosomething();
				}
			}

			break;

		case PHOTO_REQUEST_CUT:
//			if (data != null)
//				setPicToView(data);
			setPicToView();
			
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);

	}

	private void startPhotoZoom(Uri uri) {

		Uri imageUri = Uri.parse("file:///"+SIMAGE_FILE_LOCATION);//The Uri to store the big bitmap
		
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// crop为true是设置在开启的intent中设置显示的view可以剪裁
		intent.putExtra("crop", "true");

//		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
//
//		// outputX,outputY 是剪裁图片的宽高
		intent.putExtra("outputX", size);
		intent.putExtra("outputY", size);
		intent.putExtra("return-data", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	// 将进行剪裁后的图片显示到UI界面上
	private void setPicToView(Intent picdata) {
		Bundle bundle = picdata.getExtras();
		if (bundle != null) {
			Bitmap photo = (Bitmap) bundle.get("data");
			smallpic_file = saveMyBitmap(System.currentTimeMillis() + ".jpg",
					photo);
			if (mcallback != null)
				mcallback.dosomething();
		}
	}

	
	// 将进行剪裁后的图片显示到UI界面上
	private void setPicToView() {
		File file = new File(SIMAGE_FILE_LOCATION);
		if(file.exists())
		{
			smallpic_file = file;
			if (mcallback != null)
				mcallback.dosomething();
		}
	}
	public File saveMyBitmap(String bitName, Bitmap mBitmap) {
		File file = null;
		String filename = bitName == null ? System.currentTimeMillis() + ".jpg": bitName;
		try {
			if (!new File(dirPath).exists()) {
				new File(dirPath).mkdirs();
			}

			file = new File(dirPath + filename);

			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();
			FileOutputStream  fOut = new FileOutputStream(file);
			mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
			fOut.flush();
			fOut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return file;
	}

	public interface Callback {
		void dosomething();
	}

 
}
